<!-- src/views/AttractionDetail.vue -->
<template>
    <el-dialog v-model="dialogVisible" title="景点详情" width="80%" :before-close="handleClose" class="attraction-dialog"
        align-center>
        <div class="attraction-detail">
            <div class="attraction-header">
                <el-image :src="attraction.image" fit="cover" class="attraction-image" />
                <div class="attraction-info">
                    <div class="title-section">
                        <h1><strong>{{ attraction.name }}</strong></h1>
                        <div class="stats">
                            <el-rate v-model="attraction.attractionRating" disabled show-score text-color="#ff9900" />
                            <div class="like-section">
                                <el-button type="primary" text @click="toggleLike">
                                    <img :src="isLiked ? thumbLikedIcon : thumbIcon" class="thumb-icon"
                                        :alt="isLiked ? '已点赞' : '点赞'" />
                                    {{ attraction.likeCount }}
                                </el-button>
                            </div>
                        </div>
                    </div>

                    <div class="details">
                        <div class="details-row">
                            <p><strong>地址：</strong>{{ attraction.address }}</p>
                        </div>
                        <div class="details-row">
                            <p><strong>开放时间：</strong>{{ attraction.openingHours }}</p>
                        </div>
                        <div class="details-row">
                            <p><strong>票价区间：</strong>{{ attraction.priceRange }}</p>
                        </div>
                        <div class="details-row">
                            <p><strong>建议游览时间：</strong>{{ attraction.recommendedVisitTime }}</p>
                        </div>
                        <div class="details-row">
                            <p><strong>最佳游览季节：</strong>{{ attraction.recommendedVisitSeason }}</p>
                            <el-button type="primary" @click="addToPlan" class="add-plan-btn">
                                添加到我的规划
                            </el-button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="description">
                <h2 style="margin-bottom: 10px;"><strong>景点介绍</strong></h2>
                <p v-html="attraction.description.replace(/\n/g, '<br>')"></p>
            </div>

            <CommentSection :attraction-id="attractionId" />
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import { onBeforeMount, onMounted, ref, watch } from 'vue'
import thumbIcon from '@/assets/thumb.png'
import thumbLikedIcon from '@/assets/thumb_liked.png'
import CommentSection from "@/components/attractionDetail/CommentSection.vue"
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/UserStore'
import { likeAttraction } from '@/api/Attraction'
import { getAttractionInfo } from '@/api/Attraction' 
const props = defineProps<{
    visible: boolean
    attractionId: number
    attraction?: any
}>()
const emit = defineEmits(['update:visible', 'close', 'addSpot'])
const attraction = ref({} as any)
const dialogVisible = ref(props.visible)
const attractionId = ref<number | null>(null)
const isLiked = ref(false)
const userStore = useUserStore()
const userId = ref(userStore.userInfo?.userId)

// 加载景点详情
const fetchAttractionDetail = async (id: number) => {
  try {
    const response = await getAttractionInfo(id)
    if (response && response.data) {
      isLiked.value = response.data.isLikedByCurrentUser
    }
  } catch (error) {
    ElMessage.error('获取景点详情失败')
  }
}

//关闭弹窗
const handleClose = () => {
    dialogVisible.value = false
}

// 从详情页添加到规划
const addToPlan = () => {
    if (!attraction.value) {
        ElMessage.error('景点信息不完整')
        return
    }
    const spotData = {
        attractionId: attraction.value.attractionId,
        regionId: attraction.value.regionId,
        name: attraction.value.name,
        description: attraction.value.description,
        address: attraction.value.address,
        image: attraction.value.image,
        latitude: attraction.value.latitude,
        longitude: attraction.value.longitude,
        priceRange: attraction.value.priceRange,
        openingHours: attraction.value.openingHours,
        likeCount: attraction.value.likeCount,
        commentCount: attraction.value.commentCount,
        attractionRating: attraction.value.attractionRating,
        recommendedVisitTime: attraction.value.recommendedVisitTime,
        recommendedVisitSeason: attraction.value.recommendedVisitSeason,
        selectCount: attraction.value.selectCount
    }
    emit('addSpot', spotData)
}

//处理点赞事件
const toggleLike = async () => {
  if (!userId.value) {
    ElMessage.warning('请先登录')
    return
  }
  
  try {
    const res = await likeAttraction(userId.value, attraction.value.attractionId) as any
    if (res.status === 'success') { 
      isLiked.value = !isLiked.value
      attraction.value.likeCount = isLiked.value
        ? attraction.value.likeCount + 1
        : attraction.value.likeCount - 1
      ElMessage.success(isLiked.value ? '点赞成功' : '已取消点赞')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

watch(() => props.attraction, (newAttraction) => {
    if (newAttraction) {
        attraction.value = newAttraction
        attractionId.value = props.attractionId
        isLiked.value = newAttraction.isLikedByCurrentUser // 设置初始点赞状态
    }
}, { immediate: true })
watch(() => props.visible, (val) => {
    dialogVisible.value = val
})

watch(dialogVisible, (val) => {
    emit('update:visible', val)
    if (!val) {
        emit('close')
    }
})
watch(() => props.attraction, (newAttraction) => {
    if (newAttraction) {
        attraction.value = newAttraction
        attractionId.value = props.attractionId
    }
}, { immediate: true })

watch(() => props.attractionId, async (newId) => {
  if (newId) {
    await fetchAttractionDetail(newId)
  }
}, { immediate: true })
</script>

<style scoped>
strong {
    font-weight: bold;
}

:deep(.el-dialog) {
    margin-top: 5vh !important;
}

.attraction-dialog :deep(.el-dialog__body) {
    padding: 0;
}

.attraction-detail {
    padding: 20px;
    max-height: 80vh;
    overflow-y: auto;
}

.attraction-header {
    display: flex;
    gap: 20px;
}

.attraction-image {
    width: 300px;
    height: 200px;
    border-radius: 8px;
}

.attraction-info {
    flex: 1;
}

.title-section {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
}

.title-section h1 {
    margin: 0;
    font-size: 24px;
}

.stats {
    display: flex;
    align-items: center;
    gap: 20px;
}

.details {
    margin-bottom: 20px;
}

.details-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 8px 0;
}

.details-row p {
    margin: 0;
}

.add-plan-btn {
    flex-shrink: 0;
}

.description {
    margin-bottom: 20px;
}

.description h3 {
    margin-bottom: 10px;
}
</style>